// pages/autoplant/main_page.js
var autoplant_public = require('autoplant_public.js');
var ble_master = require('../ble/ble_master.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    bleServiceUUID: autoplant_public.autoPlant_ble_value.bleServiceUUID,
    bleCharUUID: autoplant_public.autoPlant_ble_value.bleCharUUID,

    plant1Num: autoplant_public.autoPlant_ble_value.plant1Num,
    plant2Num: autoplant_public.autoPlant_ble_value.plant2Num,
    splitChar: autoplant_public.autoPlant_ble_value.splitChar,

    mainPageTimer: null,
    mainPageTimerInterval: 1000,
    mainPageCmdList: [],
    mainPageCmdListIndex: 0,

    plant1CurrenADValue: 0,
    plant1MinADValue: 0,
    plant1MaxADValue: autoplant_public.autoPlant_ble_value.deviceADMaxValue,

    plant2CurrenADValue: 0,
    plant2MinADValue: 0,
    plant2MaxADValue: autoplant_public.autoPlant_ble_value.deviceADMaxValue,

    environmentCurrentTemperature: 0,
    environmentMinTemperature: autoplant_public.autoPlant_ble_value.environmentMinTemperature,
    environmentMaxTemperature: autoplant_public.autoPlant_ble_value.environmentMaxTemperature,

    environmentCurrentHumidity: 0,
    environmentMinHumidity: autoplant_public.autoPlant_ble_value.environmentMinHumidity,
    environmentMaxHumidity: autoplant_public.autoPlant_ble_value.environmentMaxHumidity,

    systemCurrentBattery: 0,
    systemMinBattery: autoplant_public.autoPlant_ble_value.systemMinBattery,
    systemMaxBattery: autoplant_public.autoPlant_ble_value.systemMaxBattery, 

    mainPageGoingtoNextPage: false,

    mainPageLastUpdateTime: "00:00:00",

    mainPageBLEConnectColor: "green",
    mainPageBLEDisonnectColor: "red",
    mainPageBLEConnecString: "Connected",
    mainPageBLEDisconnecString: "Disconnected",
    mainPageBLEConnectStateColor: "red",
    mainPageBLEConnectStateString: "Disconnected",
  },

  mainTimerCallback: function() {
    if(this.data.mainPageCmdListIndex >= this.data.mainPageCmdList.length) {
      this.data.mainPageCmdListIndex = 0
    } 
    let send_ble_cmd = this.data.mainPageCmdList[this.data.mainPageCmdListIndex]
    this.data.mainPageCmdListIndex++

    // console.log(send_ble_cmd)
    send_ble_cmd = ble_master.getCharsFromString(send_ble_cmd)
    console.log(send_ble_cmd)
    this.ble_sendData(send_ble_cmd)
  },

  initMainPageTimer: function() {
    this.data.mainPageTimer = setInterval(this.mainTimerCallback, this.data.mainPageTimerInterval)
  },

  deinitMainPageTimer: function() {
    clearInterval(this.data.mainPageTimer)
  },

  mainPageInitCmdList: function(res) {
    this.data.mainPageCmdList = []

    // Get plant 1 wet
    this.data.mainPageCmdList.push(autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.plantWet + this.data.plant1Num)
    // Get plant 2 wet
    this.data.mainPageCmdList.push(autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.plantWet + this.data.plant2Num)
    // Get environment temperature
    this.data.mainPageCmdList.push(autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.environmentTemperature)
    // Get environment humidity
    this.data.mainPageCmdList.push(autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.environmentHumidity)
    // Get device battery voltage
    this.data.mainPageCmdList.push(autoplant_public.autoPlant_ble_value.getCMDHead + autoplant_public.autoPlant_ble_value.systemBattery)

    this.data.mainPageCmdListIndex = 0

    console.log(this.data.mainPageCmdList)
  },

  ble_sendData: function(res) {
    if(ble_master.data.isConnected) {
      ble_master.ble_sendData(res)
    } else {
      console.log("ble device not connect")
    }
  },

  ble_handleReceivedData: function(head, value) {
    let date = new Date()
    let time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()

    if (head == (autoplant_public.autoPlant_ble_value.plantWet + this.data.plant1Num)) {
      // Limit the data plant1 ad
      if (value > this.data.plant1MaxADValue) {
        value = this.data.plant1MaxADValue
      }
      this.setData({
        mainPageLastUpdateTime: time,
        plant1CurrenADValue: value
      })
    } else if (head == (autoplant_public.autoPlant_ble_value.plantWet + this.data.plant2Num)) {
      // Limit the data plant2 ad
      if(value > this.data.plant2MaxADValue) {
        value = this.data.plant2MaxADValue
      }
      this.setData({
        mainPageLastUpdateTime: time,
        plant2CurrenADValue: value
      })
    } else if(head == (autoplant_public.autoPlant_ble_value.environmentTemperature)) {
      // Limit the data temperature
      if (value > this.data.environmentMaxTemperature) {
        value = this.data.environmentMaxTemperature
      }
      this.setData({
        mainPageLastUpdateTime: time,
        environmentCurrentTemperature: value
      })
    } else if (head == (autoplant_public.autoPlant_ble_value.environmentHumidity)) {
      // Limit the data humidity
      if (value > this.data.environmentMaxHumidity) {
        value = this.data.environmentMaxHumidity
      }
      this.setData({
        mainPageLastUpdateTime: time,
        environmentCurrentHumidity: value
      })
    } else if (head == (autoplant_public.autoPlant_ble_value.systemBattery)) {
      // Limit the data battery
      if (value > this.data.systemMaxBattery) {
        value = this.data.systemMaxBattery
      }
      this.setData({
        mainPageLastUpdateTime: time,
        systemCurrentBattery: value
      })
    }
  },

  ble_getNotifyDataCallback: function(res) {
    let str = ble_master.getStringFromBuffer(res)
    // console.log("Get notify data: " + str)
    let split_str = str.split(this.data.splitChar)
    if(2 == split_str.length) {
      let cmd_head = split_str[0]
      let cmd_value = ble_master.getIntFromString(split_str[1])
      console.log(cmd_head + " " + cmd_value)
      this.ble_handleReceivedData(cmd_head, cmd_value)
    } else {
      console.log("Get wrong data")
    }
  },

  ble_turnOnNotifySuccessCallback: function() {
    console.log("Trun on notify success in callback function")
    ble_master.ble_getNotifyData(this.ble_getNotifyDataCallback)
    this.mainPageInitCmdList()
    this.initMainPageTimer()
  },

  ble_connectSuccessCallback: function() {
    console.log("Connect to ble device " + ble_master.data.ble_device.deviceId + " success")
    this.setData({
      mainPageBLEConnectStateColor: this.data.mainPageBLEConnectColor,
      mainPageBLEConnectStateString: this.data.mainPageBLEConnecString
    })
    wx.showToast({
      title: '蓝牙已连接!',
    })
    if (false == ble_master.data.isNotifyOn) {
      ble_master.ble_turnOnNotify(this.data.bleServiceUUID, this.data.bleCharUUID, this.ble_turnOnNotifySuccessCallback)
    } else {
      console.log("the is notify on state is " + ble_master.data.isNotifyOn )
      this.ble_turnOnNotifySuccessCallback()
    }
    
    
  },

  ble_foundSpecialDev: function () {
    ble_master.ble_onDeviceFound(this.christp_foundBluetoothDeviceCallback)
    ble_master.ble_openAdaptorandStartDiscovery()
  },

  // Find the device and stop discovery
  christp_foundBluetoothDeviceCallback() {
    if (ble_master.ble_getDeviceinFoundDeviceListByName(autoplant_public.autoPlant_ble_value.planterDeviceName)) {
      ble_master.ble_stopDiscovery(this.christp_afterStopBluetoothDiscovery)
    }
  },

  christp_afterStopBluetoothDiscovery() {
    // this.christp_jumpToAutoPlantPage()
    console.log("device found")
    ble_master.ble_connectToDevice(this.ble_connectSuccessCallback)
  },

  ble_init: function() {
    if (ble_master.data.ble_device) {
      if(!ble_master.data.isConnected) {
        this.setData({
          mainPageBLEConnectStateColor: this.data.mainPageBLEDisonnectColor,
          mainPageBLEConnectStateString: this.data.mainPageBLEDisconnecString
        })
        ble_master.ble_connectToDevice(this.ble_connectSuccessCallback)
      } else {
        // wx.showToast({
        //   title: "Bluetooth already connect",
        // })
        this.ble_connectSuccessCallback()
      }
    } else {
      this.ble_foundSpecialDev()
    }
  },

  // christp_afterStopBluetoothDiscovery() {

  //   this.christp_jumpToAutoPlantPage()
  // },

  // Find the device and stop discovery
  christp_foundBluetoothDeviceCallback() {
    if (ble_master.ble_getDeviceinFoundDeviceListByName(autoplant_public.autoPlant_ble_value.planterDeviceName)) {
      ble_master.ble_stopDiscovery(this.christp_afterStopBluetoothDiscovery)
    }
  },

  // readyToGoSettingPage: function() {

  // },

  goSettingPage: function() {
    this.data.mainPageGoingtoNextPage = true
    wx.navigateTo({
      url: 'setting_page',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("main page load")
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("main page ready")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("main show")
    this.data.mainPageGoingtoNextPage = false
    this.ble_init()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("main hide")
    this.deinitMainPageTimer()
    if (!this.data.mainPageGoingtoNextPage) {
      ble_master.ble_disconnect()
      this.setData({
        mainPageBLEConnectStateColor: this.data.mainPageBLEDisonnectColor,
        mainPageBLEConnectStateString: this.data.mainPageBLEDisconnecString
      })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("main unload")
    this.deinitMainPageTimer()
    ble_master.ble_disconnect()
    this.setData({
      mainPageBLEConnectStateColor: this.data.mainPageBLEDisonnectColor,
      mainPageBLEConnectStateString: this.data.mainPageBLEDisconnecString
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})